import React, { memo, useEffect, useRef, useState } from "react";
import type { FC, ReactNode } from "react";
import { PlayerBarWrapper } from "./style";
import { Drawer, Slider } from "antd"
import { useAppDispatch, useAppSelector } from "@/store";
import { shallowEqual } from "react-redux";
import { changeMusicAction, changeSongModeTypeAction } from "../store";
import { formatBgColor, formatTime, formatUrlSize } from "@/utils/format";
import { HeartOutlined } from "@ant-design/icons"
import classNames from "classnames";

interface IProps {
  children?: ReactNode;
}

const PlayerBar: FC<IProps> = () => {
  // 获取store中的数据
  const { playSongInfo, songUrl, modeType, lyrics } = useAppSelector((state) => ({
    playSongInfo: state.player.playSongInfo,
    songUrl: state.player.songUrl,
    modeType: state.player.modeType,
    lyrics: state.player.lyric
  }), shallowEqual)

  // 是否是播放状态
  const [isPlay, setIsPlay] = useState(true)
  // 音量值
  const [volume, setVolume] = useState(10)
  // 歌曲进度
  const [Schedule, setSchedule] = useState(0)
  // 当前歌曲播放时间
  const [currTime, setCurrTime] = useState(0)
  // 是否处于滚动状态
  const [isRoll, setIsRoll] = useState(false)
  // 获取背景的颜色
  const [coverBg, setCoverBg] = useState("")
  // 当前播放的歌词索引
  const [currlyricIndex, setCurrlyricIndex] = useState(0)

  // 获取audio这个标签元素
  const AudioRef = useRef<HTMLAudioElement>(null)

  const dispatch = useAppDispatch()
  useEffect(() => {
    if (songUrl) {
      AudioRef.current!.src = songUrl
    }
    document.title = `${playSongInfo.name} - CoderKuMusic`

    AudioRef.current?.play().then(() => {
      setIsPlay(true)
    }).catch((err) => {
      console.log("歌曲播放失败", err)
      setIsPlay(false)
    })
    formatBgColor(playSongInfo.al.picUrl).then(res => {
      setCoverBg(res)
    })


  }, [songUrl, playSongInfo])

  // 暂停/播放事件
  const handlePlayClick = () => {
    isPlay ? AudioRef.current?.pause() : AudioRef.current?.play()
    setIsPlay(!isPlay)
  }
  // 调用音量
  const hanldeVolumeChange = (value: number) => {
    setVolume(value)
    AudioRef.current!.volume = (value / 100)
  }
  // 滚动条的滚动
  const handlePlayChange = (value: number) => {
    setIsRoll(true)
    // 总时长 (秒)
    if (!isRoll) {
      const totalTime = Math.floor(playSongInfo.dt / 1000)
      // 当前的时间 (单位/秒)
      AudioRef.current!.currentTime = totalTime * (value / 100)
    }
    setSchedule(value)
    // console.log(formatTime(playSongInfo.dt))
  }
  // 
  const drawerLyricRef = useRef<HTMLDivElement>(null)
  // 歌曲播放
  const handleTimePlay = () => {
    if (!isRoll) {
      // 当前播放时间
      setCurrTime(AudioRef.current!.currentTime)
      // 总时长 (秒)
      const totalTime = Math.floor(playSongInfo.dt / 1000)
      // 根据播放的时间 设置滚动条
      setSchedule(currTime / totalTime * 100)
    }
    for (let i = 0; i < lyrics.length; i++) {
      const item = lyrics[i];
      if (item.time > currTime * 1000) {
        if (currlyricIndex === i - 1) return;
        setCurrlyricIndex(i - 1)

        drawerLyricRef.current?.scrollTo({
          top: currlyricIndex * 80,
          behavior: "smooth",
        });
        break;
      }

    }
  }
  // 滚动条的拉跳
  const handleAfterPlayChange = (value: number) => {
    const totalTime = Math.floor(playSongInfo.dt / 1000)
    AudioRef.current!.currentTime = totalTime * (value / 100)
    setCurrTime(totalTime * (value / 100))
    setSchedule(value)
    setIsRoll(false)
  }
  // 歌曲的切换
  const handleChangeMusic = (isNext = true) => {
    dispatch(changeMusicAction(isNext))
    setCurrTime(0)
  }
  // 歌曲播放完成后
  const handleEnded = () => {
    setIsPlay(false)
    if (modeType === 2) {
      AudioRef.current!.loop = true
    } else {
      // 顺序播放和随机播放
      handleChangeMusic()
    }
    // AudioRef.current?.play()
  }
  // 播放模式的切换
  const handleChangeLoop = () => {
    dispatch(changeSongModeTypeAction())
  }
  // 歌词页面弹窗 是否显示
  const [open, setOpen] = useState(false)
  // 弹窗的控制
  const onClose = () => {
    setOpen(false)
  }
  const handledrawerOpen = () => {
    setOpen(true)
  }

  // console.log(currTime)
  return <PlayerBarWrapper isplay={Number(isPlay)} isloop={modeType} volume={volume} >
    {songUrl && <audio ref={AudioRef} src={songUrl} onEnded={handleEnded} onTimeUpdate={handleTimePlay}></audio>}
    <Slider step={.4} value={Schedule} tooltip={{ open: false }} onAfterChange={handleAfterPlayChange} onChange={handlePlayChange} />
    {
      playSongInfo &&
      <div className="playerbar-content">
        <div className="song-info">
          <img src={formatUrlSize(playSongInfo.al.picUrl, 224)} alt="歌曲封面" className="song-cover" />
          <div className="trank-info">
            <div className="name">{playSongInfo.name}</div>
            <div className="artist">{playSongInfo.ar[0].name}</div>
          </div>
        </div>
        <div className="middle-control-buttons">
          <button className="player-bg prev btn" onClick={() => handleChangeMusic(false)}></button>
          <button className="player-bg play btn" onClick={handlePlayClick}></button>
          <button className="player-bg next btn" onClick={() => handleChangeMusic()}></button>
        </div>
        <div className="right-control-buttons">
          <button className="player-bg playlist"></button>
          <button className="player-bg loop" onClick={handleChangeLoop}></button>
          <div className="volume-control">
            <div className="player-bg volume-icon"></div>
            <Slider onChange={hanldeVolumeChange} tooltip={{ open: false }} value={volume} />
          </div>
          <button className="arraw-up">
            <img src={require("@/assets/img/arraw-up.png")} onClick={handledrawerOpen} alt="歌词页面弹窗" />
          </button>
        </div>
      </div>
    }
    {playSongInfo && lyrics && <Drawer
      placement="bottom"
      width={500}
      closable={false}
      height={"100vh"}
      bodyStyle={{
        background: coverBg
      }}
      rootClassName="drawer"
      open={open}
    >
      <div className="drawer-body">
        <div style={{
          color: "#fff", display: "flex",
          justifyContent: "flex-end"
        }}>
          <button style={{ padding: "8px", cursor: "pointer" }} onClick={onClose}>
            <img style={{ width: "24px", height: "24px" }} src={require("@/assets/img/arraw-bottom.png")} alt="" />
          </button>
        </div>
        <div className="drawer-contniner">
          <div className="drawer-info">
            <div className="drawer-cover">
              <img src={formatUrlSize(playSongInfo.al.picUrl, 1024)} className="drawer-cover-img" alt="" />
            </div>
            <div className="drawer-song-message">
              <div className="drawer-topbox">
                <div className="drawer-left">
                  <div className="drawer-name">{playSongInfo.name}</div>
                  <div className="drawer-artist">{playSongInfo.ar[0].name}</div>
                </div>
                <div className="drawer-right">
                  <HeartOutlined />
                </div>
              </div>
              <div className="progress-bar">
                <div className="start-time">{formatTime(currTime)}</div>
                <div className="end-time">{formatTime(playSongInfo.dt / 1000)}</div>
              </div>
              <Slider step={.4} value={Schedule} tooltip={{ open: false }} onAfterChange={handleAfterPlayChange} onChange={handlePlayChange} />
              <div className="drawer-controller">
                <button className="player-bg prev btn" onClick={() => handleChangeMusic(false)}></button>
                {isPlay && <button className="player-bg play btn" onClick={handlePlayClick}></button>}
                {!isPlay && <button className="player-bg pause btn" onClick={handlePlayClick}></button>}
                <button className="player-bg next btn" onClick={() => handleChangeMusic()}></button>
              </div>
            </div>
          </div>
          <div className="drawer-lyric" ref={drawerLyricRef}>
            {
              lyrics.map((item, index) => (
                <div className="lyrics-item" key={item.time}>
                  <span className={classNames("lyric-text", { lyricActive: index === currlyricIndex })}>{item.text}</span>
                </div>
              ))
            }
          </div>
        </div>
      </div>
    </Drawer>}

  </PlayerBarWrapper>;
};

export default memo(PlayerBar);